package com.peas.platform.module.icims.base.auth.domain.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peas.platform.framework.mybatisplus.domain.BaseDomainImpl;
import com.peas.platform.framework.mybatisplus.repository.BaseRepository;
import com.peas.platform.module.icims.base.auth.adapter.repository.UserVisitRepository;
import com.peas.platform.module.icims.base.auth.adapter.repository.po.UserVisitPo;
import com.peas.platform.module.icims.base.auth.api.resp.UserVisitResp;
import com.peas.platform.module.icims.base.auth.domain.UserVisitDomain;
import com.peas.platform.module.icims.base.auth.dto.UserVisitDto;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class UserVisitDomainImpl extends BaseDomainImpl<UserVisitDto, UserVisitPo> implements UserVisitDomain {

    @Resource
    private UserVisitRepository userVisitRepository;

    @Override
    public BaseRepository<UserVisitPo> getMapper() {
        return userVisitRepository;
    }

    @Override
    public Class<? extends BaseRepository<UserVisitPo>> getRepositoryClass() {
        return UserVisitRepository.class;
    }

    @Override
    public List<UserVisitResp> getUserVisit(Long userId) {
        Assert.notNull(userId, "用户ID不能为空");
        UserVisitPo c = new UserVisitPo();
        c.setUserId(userId);
        QueryWrapper<UserVisitPo> wrapper = Wrappers.query(c);
        wrapper.select("user_id,title,icon,name,path,count(0) as count");
        wrapper.eq("user_id", userId);
        wrapper.groupBy(Arrays.asList("user_id", "title", "icon", "name", "path"));
        wrapper.orderByDesc("count");
        Page<Map<String, Object>> page = userVisitRepository.selectMapsPage(Page.of(1, 5), wrapper);
        if (page == null || CollUtil.isEmpty(page.getRecords())) {
            return Collections.emptyList();
        }
        List<UserVisitResp> result = new ArrayList<>();
        page.getRecords().forEach(map -> result.add(BeanUtil.toBean(map, UserVisitResp.class)));
        return result;
    }

}
